﻿// <copyright file="LoginController.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
namespace MesAPI.Controllers.Account
{
    using System.Security.Claims;
    using MesAPI.PermissionManagement.Auth;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Options;
    using PublicData;
    using PublicFunction;
    using PublicModelsAndEntities.Models.Response;
    using XinjeMesProgram.Entities;
    using XinjeMesProgram.Entities.User;

    /// <summary>
    /// LoginController.
    /// </summary>
    [ApiController]
    public class LoginController : ControllerBase
    {
        // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
        private readonly AuthenticationSettings appSettings;
        private ResponseModel response = ResponseModelFactory.CreateInstance;

        /// <summary>
        /// Initializes a new instance of the <see cref="LoginController"/> class.
        /// .
        /// </summary>
        /// <param name="appSettings">.</param>
        public LoginController(IOptions<AuthenticationSettings> appSettings)
        {
            this.appSettings = appSettings.Value;
        }

        /// <summary>
        /// 登录.
        /// </summary>
        /// <param name="username">.</param>
        /// <param name="password">1.</param>
        /// <returns>11.</returns>
        [Route("api/login")]
        [HttpGet]
        public ResponseModel Login(string username, string password)
        {
            string userRoleCode = string.Empty;

            MyLogFunction.SaveSysEventLog("用户请求登录", username);
            using (var dBcontext = new FactoryMesContext())
            {
                MesUserRole user = dBcontext.MesUserRole.FirstOrDefault(x => x.LoginName == username.Trim());
                if (user != null)
                {
                    if (user.IsLocked == XinjeMesProgram.Entities.RoleAndUser.CommonEnum.IsLocked.UnLocked)
                    {
                        if (!string.IsNullOrEmpty(user.RoleCode))
                        {
                            if (user.PWD == password)
                            {
                                var claimsIdentity = new ClaimsIdentity(new Claim[]
                                    {
                                        // new Claim("avatar", string.Empty),
                                        // new Claim("CustomerType", ((int)user.CustomerType).ToString()),
                                        // new Claim("RootTreeId", string.Empty),
                                        // new Claim("Phone", user.Phone),
                                        // new Claim("DeptName", user.Dep),
                                        new Claim(ClaimTypes.Name, username),
                                        new Claim("UserId", user.ID.ToString()),
                                        new Claim("UserName", user.UserName),
                                        new Claim("userType", ((int)user.UserType).ToString()),
                                        new Claim("RegGroupId", user.RegGroupId),
                                        new Claim("RoleCode", user.RoleCode),
                                        new Claim("DepName", user.Dep),
                                        new Claim("DepId", user.DepId),
                                        new Claim("GroupType", user.GroupType),
                                        new Claim("ProductGroup", user.ProductGroup),
                                    });

                                var token = JwtAuthentication.GetJwtAccessToken(this.appSettings, claimsIdentity);
                                this.response.SetToken(token);
                                MyLogFunction.SaveSysEventLog("登录成功", username + "," + user.ID);
                            }
                            else
                            {
                                this.response.SetError("密码错误");
                            }
                        }
                        else
                        {
                            this.response.SetError("尚未给该用户分配权限！");
                        }
                    }
                    else
                    {
                        this.response.SetError("该账户已被禁用！");
                    }
                }
                else
                {
                    this.response.SetError("用户不存在");
                }
            }

            return this.response;
        }

        /// <summary>
        /// 获取加密公钥.
        /// </summary>
        /// <returns>.</returns>
        [Route("api/v1/get_public_key")]
        [HttpGet]
        public ResponseModel Get_public_key()
        {
            this.response.SetData("Xinje_Mes V1.0", MyEncrypt1.PublicKey);
            return this.response;
        }
    }
}
